package edu.tjut.service;

import java.util.Arrays;
import java.util.List;
import java.util.Locale;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.javafaker.Faker;

import edu.tjut.dao.CustomerDao;
import edu.tjut.dao.OrderDao;
import edu.tjut.dao.ProductDao;
import edu.tjut.domain.Customer;
import edu.tjut.domain.OrderLine;
import edu.tjut.domain.Order;
import edu.tjut.domain.OrderState;
import edu.tjut.domain.Product;

@Service
public class BuyService {
	@Autowired
	private CustomerDao customerDao;
	@Autowired
	private ProductDao productDao;
	@Autowired
	private OrderDao orderDao;
	
	Faker faker = Faker.instance(Locale.CHINA);
	
	@Transactional
	public void buy(long customer_id, Long[] product_ids) {
		Customer customer = customerDao.getOne(customer_id);
		List<Product> products = productDao.findAllById(Arrays.asList(product_ids));
		Order order = new Order(customer, customer.getAddresses().iterator().next(), OrderState.APPROVED);
		for (Product product : products) {
			order.addOrderLine(new OrderLine(product, faker.number().randomDigitNotZero()));
		}
		orderDao.save(order);
	}
}
